<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警示框 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 商品添加步骤条 -->
      <el-steps
        :active="activeName - 0"
        align-center
        class="m_top"
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="精美图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form
        :model="tabsruleForm"
        :rules="tabsrules"
        ref="tabsruleForm"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="tabPosition"
          class="m_top1"
          v-model="activeName"
          :before-leave="tabhandle"
          @tab-click="manyTabscates"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="tabsruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="tabsruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="tabsruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="tabsruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="tabsruleForm.goods_cat"
                :options="datalistcate"
                :props="paramsprops"
                @change="cascaderhandleChange"
                expandTrigger="hover"
                class="add_cas"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabsdata"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabsdata"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="精美图片">
            <el-upload
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="successUpload"
              :headers="header"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="tabsruleForm.goods_introduce">
            </quill-editor>
            <el-button type="primary" class="addbtn" @click="addgoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- dialog对话框 -->
      <el-dialog title="提示" :visible.sync="imgdialogVisible" width="50%">
        <img :src="imgSrc" alt="" class="uploadImg" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      imgdialogVisible: false,
      // 上传图片的src
      imgSrc: '',
      // 获取商品属性
      onlyTabsdata: [],
      // 存储获取到的商品参数
      manyTabsdata: [],
      // 商品分类列表
      datalistcate: [],
      tabPosition: 'left',
      // 这是tabs点击不同的产生的
      activeName: '0',
      // tabs里面的表单
      tabsruleForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单验证规则
      tabsrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 级联选择框选择结果
      cascadervalue: '',
      // 级联选择对象
      paramsprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      header: {
        Authorization: window.sessionStorage.getItem('token')
      }
    }
  },
  created() {
    this.getlistcate()
  },
  methods: {
    async getlistcate() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200) {
        return
      }
      this.datalistcate = res.data
    },
    // 级联选择框改变事件
    cascaderhandleChange() {
      console.log(this.tabsruleForm.goods_cat)
    },
    // tabs的切换监听函数
    tabhandle(activeName, oldActiveName) {
      // console.log(oldActiveName)
      if (oldActiveName === '0' && this.tabsruleForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类后切换')
        return false
      }
    },
    // 这是tabs点击的监听函数
    async manyTabscates() {
      // console.log(this.activeName)
      if (this.activeName === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        // console.log(res)
        res.data.forEach((ele) => {
          ele.attr_vals = ele.attr_vals !== '' ? ele.attr_vals.split(' ') : []
        })
        this.manyTabsdata = res.data
        // console.log(this.manyTabsdata)
      }
      // 判断是否是点击的商品属性
      if (this.activeName === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.message.error('获取商品属性失败')
        }
        this.onlyTabsdata = res.data
        console.log(this.onlyTabsdata)
      }
    },
    // 监听处理图片的钩子 实现图片的预览效果
    handlePreview(imgfilter) {
      this.imgdialogVisible = true
      console.log(imgfilter)
      this.imgSrc =
        'http://www.ysqorz.top:8888/' + imgfilter.response.data.tmp_path
    },
    // 监听图片点击删除的钩子
    handleRemove(filter) {
      // console.log(filter)
      // 拿到返回值中的tem_path
      // 利用数组的findIndex方法查找和返回值相同的对应索引
      const filterindex = filter.response.data.tmp_path
      const index = this.tabsruleForm.pics.findIndex(
        (item) => item.tmp_path === filterindex
      )
      this.tabsruleForm.pics.splice(index, 1)
    },
    // 监听上传成功的钩子
    successUpload(response) {
      console.log(response)
      if (response.meta.status !== 200) {
        return this.$message.error('上传失败')
      }
      const picObj = {
        pic: '/' + response.data.tmp_path
      }
      this.tabsruleForm.pics.push(picObj)
      console.log(this.tabsruleForm.pics)
    },
    // 添加商品
    async addgoods() {
      // 进行表单预验证
      this.$refs.tabsruleForm.validate(async (validate) => {
        if (!validate) {
          return this.$message.error('请输入正确的信息')
        }
        // 成功之后进行
        // 进行attrs的push 处理动态参数
        this.manyTabsdata.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.tabsruleForm.attrs.push(newInfo)
        })
        // 处理静态属性
        // console.log(this.onlyTabsdata)
        this.onlyTabsdata.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.tabsruleForm.attrs.push(newInfo)
        })
        // const form = this.tabsruleForm
        const form = _.cloneDeep(this.tabsruleForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form)
        // 发起请求
        const { data: res } = await this.$http.post('goods', form)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 利用计算属性返回选中的id
    cateID() {
      if (this.tabsruleForm.goods_cat.length === 3) {
        return this.tabsruleForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.m_top {
  margin-top: 15px !important;
  font-size: 12px !important;
}
.m_top1 {
  margin-top: 20px;
}
.add_cas {
  width: 300px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.uploadImg {
  width: 100%;
}
.addbtn {
  margin-top: 10px;
}
</style>